<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="form.id ? '编辑' : '新增'"
    width="620"
    height="800"
    show-footer
    show-zoom
    resize
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <template #default>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-align="right"
        label-width="120"
        size="default"
        label-position="top"
      >
        <el-row :gutter="20">
          <el-col :span="21">
            <el-form-item label="模版名称" prop="template_name">
              <el-input v-model="form.template_name" placeholder="模版名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" class="mt-7">
            <el-form-item label="" label-width="0" prop="status">
              <el-switch
                v-model="form.status"
                :active-value="0"
                :inactive-value="1"
                active-text="启用"
                inactive-text="禁用"
                inline-prompt
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="绑定产品分类" prop="attribute_class">
          <select-category
            class="w-full"
            v-model="form.attribute_class"
            :showAllLevels="true"
          ></select-category>
          <select-category
            class="w-full"
            v-model="form.attribute_class"
            :showAllLevels="true"
          ></select-category>
          <!-- <el-cascader v-model="form.attribute_class" :options="props.treeData" :props="defaultProps" placeholder="请选择"
            clearable class="w-full" /> -->
        </el-form-item>
        <el-form-item label="销售属性" prop="attribute">
          <div
            class="bg-[var(--base-small-bg-color)] w-full py-2 px-2"
            v-for="(item, index) in form.attribute"
            :key="index"
          >
            <div>
              <div>{{ item.label }}</div>
              <div class="flex">
                <el-input
                  class="mr-2"
                  v-model="item.label_name"
                  placeholder="请输入字段"
                ></el-input>
                <svg-icon
                  icon-class="jian"
                  v-if="index == form.attribute.length - 1"
                  class="mr-2"
                  @click="itemReduce(index)"
                ></svg-icon>

                <svg-icon icon-class="add" @click="itemAdd()"></svg-icon>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save(formRef)">保 存</el-button>
    </template>
  </el-dialog>
</template>
<script setup name="ComModal" lang="jsx">
import { attributeDetail, attributeSave, attributeUpdate } from "../api/index";
import { reactive, ref, toRefs, getCurrentInstance } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import SelectCategory from "@/components/SelectCategory";

const visible = ref(false);
const loading = ref(false);
const formRef = ref(null);
const emits = defineEmits(["query"]);
const { proxy } = getCurrentInstance();
const props = defineProps({
  treeData: {
    type: Array,
    default: () => [],
  },
});
const defaultProps = {
  children: "son",
  label: "name",
  value: "id",
  checkStrictly: true,
};
const data = reactive({
  form: {},
  rules: {
    template_name: [{ required: true, message: "请输入模版名称" }],
    attribute_class: [{ required: true, message: "请选择产品分类", trigger: "change" }],
    attribute: [{ required: true }],
  },
  load: false,
});
const { rules, form, load } = toRefs(data);
const open = async (id) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  visible.value = true;
  if (id) getDetail(id);
};

const initForm = () => {
  form.value = getForm();
};
// 初始化
const getForm = () => {
  return {
    template_name: "",
    status: 0,
    attribute_class: [],
    attribute: [
      {
        label: "自定义属性1",
        label_name: "",
        sort: "1",
      },
    ],
  };
};

onMounted(() => {
  initForm();
});

const getDetail = async (id) => {
  try {
    const res = await attributeDetail({
      id,
    });
    form.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};

const itemReduce = (index) => {
  form.value.attribute.splice(index, 1);
};

const itemAdd = () => {
  const label =
    form.value.attribute[0].label.slice(0, -1) + (form.value.attribute.length + 1);
  form.value.attribute.push({
    label: label,
    label_name: "",
  });
};

const save = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      // loading.value = true
      let massageArray = [];
      form.value.attribute.length &&
        form.value.attribute.forEach((element, index) => {
          if (!element.label_name) {
            massageArray.push(`请输入第 ${index + 1} 列自定义属性`);
          }
        });
      if (massageArray && massageArray.length) {
        ElMessageBox({
          title: "提示",
          message: () => <div>{massageArray.map((d) => h("p", null, d))}</div>,
        });
        return;
      }

      if (form.value.id) {
        attributeUpdate(form.value)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally((e) => {
            loading.value = false;
          });
      } else {
        attributeSave(form.value)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally((e) => {
            loading.value = false;
          });
      }
    }
  });
};
const close = () => {
  initForm();
  proxy.resetForm("formRef");
  visible.value = false;
};
defineExpose({ open });
</script>
